<template>
    <!-- 检索栏 -->
    <a-form class="smart-query-form" :model="queryParams" ref="queryRef" layout="inline" v-show="showSearch"
        :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
        <a-row class="smart-query-form-row">
            <a-form-item label="流程名称" name="processName" class="smart-query-form-item">
                <a-input v-model:value="queryParams.processName" placeholder="请输入流程名称" allowClear
                    @pressEnter="handleQuery" />
            </a-form-item>
            <a-form-item label="流程标识" name="processKey" class="smart-query-form-item">
                <a-input v-model:value="queryParams.processKey" placeholder="请输入流程标识" allowClear
                    @pressEnter="handleQuery" />
            </a-form-item>
            <a-form-item label="流程分类" name="category" class="smart-query-form-item">
                <a-select v-model:value="queryParams.category" placeholder="流程分类" allowClear style="width: 240px">
                    <a-select-option v-for="item in flowCategory" :key="item.code" :value="item.code">
                        {{ item.name }}
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="状态" name="state" class="smart-query-form-item">
                <a-select v-model:value="state" size="small" allowClear style="width: 100px;" placeholder="请选择状态">
                    <a-select-option :value="'active'">激活</a-select-option>
                    <a-select-option :value="'suspended'">挂起</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item class="smart-query-form-item">
                <a-button-group>
                    <a-button type="primary" @click="handleQuery" v-privilege="'flow:flow_model:list'">
                        <template #icon>
                            <SearchOutlined />
                        </template>
                        查询
                    </a-button>
                    <a-button @click="resetQuery" v-privilege="'flow:flow_model:list'">
                        <template #icon>
                            <ReloadOutlined />
                        </template>
                        重置
                    </a-button>
                </a-button-group>
            </a-form-item>
        </a-row>
    </a-form>

    <a-card size="small" :bordered="false" :hoverable="true">
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
                <a-button type="primary" danger :disabled="selectedRowKeyList.length === 0" @click="handleDelete"
                    v-privilege="['flowable:deploy:remove']">
                    <template #icon>
                        <DeleteOutlined />
                    </template>
                    删除
                </a-button>
            </div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="columns" :refresh="getList" />
            </div>
        </a-row>

        <a-table size="small" :dataSource="taskList" :pagination="false" rowKey="procInsId"
            :rowSelection="{ selectedRowKeys: selectedRowKeyList, onChange: handleSelectionChange }">
            <a-table-column title="流程编号" align="center" :ellipsis="true">
                <template #default="{ record }">
                    <a-button type="link" @click="handleProcessView(record)">
                        {{ record.procInsId }}
                    </a-button>
                </template>
            </a-table-column>
            <a-table-column title="流程名称" dataIndex="procDefName" align="center" />
            <a-table-column title="流程分类" dataIndex="category" align="center">
                <template #default="{ record }">
                    {{ categoryFormat(record) }}
                </template>
            </a-table-column>
            <a-table-column title="流程版本" align="center" width="100">
                <template #default="{ record }">
                    <a-tag size="small">v{{ record.procDefVersion }}</a-tag>
                </template>
            </a-table-column>
            <a-table-column title="提交时间" dataIndex="createTime" align="center">
                <template #default="{ record }">
                    <span>{{ parseTime(record.createTime) }}</span>
                </template>
            </a-table-column>
            <a-table-column title="流程状态" align="center">
                <template #default="{ record }">
                    <a-tag v-if="record.finishTime == null && record.assigneeName == null" color="success">
                        {{ '进行中' }}
                    </a-tag>
                    <a-tag v-if="record.finishTime != null && record.assigneeName == null" color="warning">
                        {{ '已完成' }}
                    </a-tag>
                    <a-tag v-if="record.assigneeName != null">
                        {{ '已取消' }}
                    </a-tag>
                </template>
            </a-table-column>
            <a-table-column title="耗时" dataIndex="duration" align="center" />
            <a-table-column title="操作" align="center" width="280">
                <template #default="{ record }">
                    <a-space>
                        <a-button type="link" size="small" :disabled="record.finishTime != null"
                            @click="handleCancel(record)">
                            <template #icon>
                                <StopOutlined />
                            </template>
                            取消
                        </a-button>
                        <a-button type="link" size="small" @click="handleDelete(record)"
                            v-privilege="['flowable:deploy:remove']">
                            <template #icon>
                                <DeleteOutlined />
                            </template>
                            删除
                        </a-button>
                    </a-space>
                </template>
            </a-table-column>
        </a-table>

        <div class="smart-query-table-page">
            <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS"
                :defaultPageSize="queryForm.pageSize" v-model:current="queryForm.pageNum"
                v-model:pageSize="queryForm.pageSize" :total="total" @change="getList" @showSizeChange="getList"
                :show-total="(total) => `共${total}条`" />
        </div>
    </a-card>

    <!-- 流程查看界面-->
    <ProcessView
        :title="processView.title"
        :open="processView.open"
        @update:open="val => processView.open = val"
        :deployId="processView.modelId"
        :procInsId="processView.procInsId"
    />

</template>

<script setup name="FlowTask">
import { ref, reactive, toRefs } from "vue";
import { message, Modal } from 'ant-design-vue';
import {
    SearchOutlined,
    ReloadOutlined,
    DeleteOutlined,
    PauseOutlined,
    PlayCircleOutlined,
    HistoryOutlined,
    StopOutlined
} from '@ant-design/icons-vue';
import { deployApi } from "/@/api/business/flowable/deploy";
import { flowTaskApi } from "/@/api/business/flowable/task";
import { categoryApi } from "/@/api/business/flowable/category";
import ProcessView from "/@/components/business/flowable/process-view/index.vue";
import InitBPMNXml from '/@/assets/bpmn/empty.bpmn20.xml?raw';
import { smartSentry } from '/@/lib/smart-sentry';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { parseTime } from "/@/components/common/util";
import TableOperator from '/@/components/support/table-operator/index.vue';
import _ from 'lodash';

const taskList = ref([]);
const open = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const flowCategory = ref([]);
const state = ref('');
const activeKeys = ref(['1']); // 默认只展开第一个面板（流程图）
const flowRecordList = ref([]); // 流程记录列表

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        definitionId: null,
        processName: null,
        processKey: null,
        category: null,
        version: null,
        deploymentId: null,
        suspended: null,
        deploymentTime: null
    },
    rules: {},
    processView: {
        title: '',
        open: false,
        modelId: undefined,
        procInsId: undefined
    },
    publishQueryParams: {
        pageNum: 1,
        pageSize: 10,
        processKey: ""
    },
    publish: {
        open: false,
        loading: false,
        dataList: []
    },
    publishTotal: 0
});
// 查询表单form
const queryForm = reactive(_.cloneDeep(data.queryParams));

const publishQueryForm = reactive(_.cloneDeep(data.publishQueryParams));

const { queryParams, form, rules, processView, publishQueryParams, publish, publishTotal } = toRefs(data);

/** 查询流程部署列表 */
async function getList() {
    SmartLoading.show()
    try {
        let res = await flowTaskApi.listTask(queryForm)
        taskList.value = res.data.list;
        total.value = res.data.total;
    } catch (e) {
        smartSentry.captureError(e)
    } finally {
        SmartLoading.hide()
    }
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        definitionId: null,
        processName: null,
        processKey: null,
        category: null,
        version: null,
        deploymentId: null,
        suspended: null,
        deploymentTime: null
    };
    // proxy.resetForm("deployRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    if (state.value) {
        queryParams.value.suspended = state.value === 'active' ? false : state.value === 'suspended' ? true : null;
    } else {
        queryParams.value.suspended = null;
    }
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    // proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selectedRowKeys) {
    ids.value = selectedRowKeys;
    single.value = selectedRowKeys.length !== 1;
    multiple.value = !selectedRowKeys.length;
    selectedRowKeyList.value = selectedRowKeys;
}

// 选择表格行
const selectedRowKeyList = ref([]);

function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys;
}

/** 查看流程图 */
function handleProcessView(row) {
    processView.value = {
        modelId: row.deployId,
        procInsId: row.procInsId,
        open: true,
        title: '流程图'
    };
}

async function getPublishList() {
    try {
        let response = await deployApi.publishList(publishQueryForm)
        publish.value = {
            dataList: response.data.rows,
            open: true,
            loading: false
        };
        publishTotal.value = response.data.total;
    } catch (e) {
        smartSentry.captureError(e)
    }
}

function handlePublish(row) {
    publishQueryForm.processKey = row.processKey;
    getPublishList();
}

/** 挂起/激活流程 */
function handleCancel(row) {
    Modal.confirm({
        title: '确认',
        content: `是否取消选中的流程任务？`,
        onOk() {
            return cancelTask(row)
        }
    })
}

async function cancelTask(row) {
    try {
        let res = await flowTaskApi.cancelTask(row.procInsId)
        if (res.ok) {
            message.success("取消成功");
        } else {
            message.error("取消失败")
        }
    } catch (e) {
        smartSentry.captureError(e)

    } finally {
        getList()
    }
}

/** 删除按钮操作 */
function handleDelete(row) {
    let procInsId = selectedRowKeyList.value
    if (row.procInsId) {
        procInsId = row.procInsId
    }
    Modal.confirm({
        title: '确认',
        content: `是否确认删除选中的流程部署？`,
        onOk() {
            if (deleteTask(procInsId)) {
                // 返回删除成功后，判断是不是批量删除，如果是的话清空已选中的键
                if (!row.procInsId) {
                    selectedRowKeyList.value = []
                }
            }
        }
    });
}

async function deleteTask(procInsId) {
    try {
        let res = await flowTaskApi.delTask(procInsId)
        if (res.ok) {
            message.success("删除成功");
        } else {
            message.error("删除失败")
        }
        
        return true
    } catch (e) {
        smartSentry.captureError(e)
        return false
    } finally {
        getList()
    }
}

/**
 * 翻译分类编码
 */
function categoryFormat(row) {
    return flowCategory.value.find(k => k.code === row.category)?.name ?? '';
}

/**
 * 获取流程分类
 */
async function getFlowCategory() {
    try {
        // 这里强制搜索大小为65536，否则查询的结果只返回默认的前10个
        let category = await categoryApi.listCategory({ pageSize: 65536 })
        flowCategory.value = category.data.rows;
    } catch (e) {
        smartSentry.captureError(e)
    }
}

// 设置时间线颜色
function setColor(finishTime) {
    return finishTime ? 'green' : 'blue';
}

getList();
getFlowCategory();
</script>

<style scoped>
.mb8 {
    margin-bottom: 8px;
}

/* 自定义滚动条样式 */
:deep(.ant-collapse-content-box) {
    padding: 0 !important;
}

:deep(.ant-timeline) {
    padding: 16px;
}

:deep(.ant-descriptions) {
    margin-bottom: 16px;
}

/* 隐藏滚动条但保持功能 */
:deep(.ant-collapse-content-box) {
    overflow-x: hidden;
}

:deep(.ant-descriptions-view) {
    overflow-x: hidden;
}
</style>